package edu.sdbi.judge.controller;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.JsonResult;
import edu.sdbi.judge.util.ErrorUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/statistics")
public class StaticData13Controller {
    public static final List<Map<String, Object>> mockNewsList = new ArrayList<>();
    public static final Map<String, Object> mockData1 = new HashMap<>();

    static {
        // 初始化模拟数据
        mockData1.put("newsId", "1");
        mockData1.put("title", "新闻标题");
        mockData1.put("visitCount", 500);
        mockData1.put("CommentCount", 400);
        mockNewsList.add(mockData1);
    }

    private static final Map<String, Object> mockData2 = new HashMap<>();

    static {
        // 初始化模拟数据
        mockData2.put("newsId", "2");
        mockData2.put("title", "新闻标题");
        mockData2.put("visitCount", 50);
        mockData2.put("CommentCount", 4);
        mockNewsList.add(mockData2);
    }


    /**
     * 模拟新闻访问统计接口
     *
     * @param newsID 新闻ID
     * @return 统计结果
     */
    @PostMapping("/compare")
    public String getNewsComparativeAnalysis(@RequestParam("newsID") String newsID) {
        try {
            // 验证新闻ID
            if (newsID == null || newsID.isEmpty()) {
                return buildErrorResult(400, "缺少必要参数: newIds");
            }

            // 分割新闻ID
            String[] idArray = newsID.split(",");
            List<String> requestedIds = Arrays.asList(idArray);

            // 过滤出请求的新闻数据
            List<Map<String, Object>> resultList = mockNewsList.stream()
                    .filter(news -> requestedIds.contains(news.get("newsId")))
                    .collect(Collectors.toList());

            // 检查是否所有请求的ID都有数据
            if (resultList.size() != requestedIds.size()) {
                return buildErrorResult(404, "部分新闻ID不存在");
            }
            // 构建成功响应
            JsonResult result = new JsonResult();
            result.setCode(200);
            result.setMsg("新增成功");
            result.setData(resultList);

            return JSONObject.toJSONString(result);
        } catch (Exception e) {
            return buildErrorResult(500, ErrorUtil.stackTraceToString(e));
        }
    }

    /**
     * 构建错误响应
     *
     * @param code    错误码
     * @param message 错误信息
     * @return 错误响应JSON字符串
     */
    private String buildErrorResult(int code, String message) {
        JsonResult result = new JsonResult();
        result.setCode(code);
        result.setMsg(message);
        return JSONObject.toJSONString(result);
    }
}
